<script setup lang="ts">
import TableView from '@/components/TableView.vue'
import {
  NButton,
  NSelect,
  NInput,
  NDataTable,
  NForm,
  NFormItem,
  NPagination,
  useMessage,
  type DataTableColumns,
  NSpace,
  NModal,
  NDatePicker,
  useDialog
} from 'naive-ui'
import { h, ref, reactive, watch, onDeactivated } from 'vue'
import router from '@/router'
import { useRoute } from 'vue-router'
import { sendRequest } from '@/utils/api'
import { useViewerStore } from '../Common/store'
import VDialogContent from '@/views/OA/Common/DialogContent.vue'
import { RecordType } from '@/router/utils'
import type { RoomItem } from '@/types/interfaces'
import dayjs from 'dayjs'

const message = useMessage()
const route = useRoute()
const useStore = useViewerStore()
const dialog = useDialog()

const formInfo: any = reactive({
  conferenceRoomId: null,
  fromStatusCode: null,
  content: null,
  startTime: null,
  endTime: null
})

const roomList = ref<RoomItem[]>([])

// 获取会议室列表
const fetchRoomList = async () => {
  const [error, res] = await sendRequest({
    module: 'meeting',
    api: 'roomList',
    override: {
      params: {
        page: 1,
        limit: 100 // 假设我们想获取所有会议室，可以设置一个较大的限制
      }
    }
  })

  if (error) {
    message.error(error.message || '获取会议室列表失败')
    return
  }

  if (res.code === 0 && res.data && Array.isArray(res.data.list)) {
    roomList.value = res.data.list.map((item: any) => ({
      label: item.name,
      value: item.id.toString(),
      info: {
        id: item.id,
        name: item.name,
        capacity: item.suggestedNumber,
        facilities: item.facility ? item.facility.split(',') : []
      }
    }))
  } else {
    message.error('获取会议室列表失败')
  }
}

const statusList = [
  { label: '撤销', value: 'A0602' },
  { label: '审批中', value: 'A0603' },
  { label: '拒绝', value: 'A0604' },
  { label: '通过', value: 'A0605' }
]

const rowKey: any = (e: any) => e.id || ''
const columns: DataTableColumns = [
  {
    title: '序号',
    key: 'conferenceRoomId',
    width: '5rem',
    align: useStore.isCenter
  },
  {
    title: '会议室',
    key: 'conferenceRoomName',
    width: '10rem',
    align: useStore.isCenter
    // render(row) {
    //   const room = roomList.value.find((item) => item.value == row.conferenceRoomId)
    //   return room ? room.label : '未知'
    // }
  },
  {
    title: '会议日期',
    key: 'applicationTime',
    width: '10rem',
    align: useStore.isCenter,
    render(row) {
      return dayjs(row.applicationTime).format('YYYY-MM-DD')
    }
  },
  {
    title: '会议时间',
    key: 'meetingTime',
    width: '10rem',
    align: useStore.isCenter,
    render(row) {
      const startTime = dayjs(row.startTime).format('HH:mm')
      const endTime = dayjs(row.endTime).format('HH:mm')
      return `${startTime}-${endTime}`
    }
  },
  {
    title: '用途',
    key: 'content',
    width: '10rem',
    align: useStore.isCenter,
    ellipsis: {
      tooltip: {
        contentStyle: 'max-width:500rem'
      }
    }
  },
  {
    title: '提交时间',
    key: 'createTime',
    width: '10rem',
    align: useStore.isCenter
  },
  {
    title: '审批状态',
    key: 'fromStatusCode',
    width: '5rem',
    align: useStore.isCenter,
    render({ fromStatusCode }) {
      const status = statusList.find((item) => item.value === fromStatusCode)
      return status ? status.label : '未知'
    }
  },

  {
    title: '操作',
    key: 'action',
    width: '15rem',
    align: useStore.isCenter,
    fixed: 'right',
    render: (e: any) => [
      h(
        NButton,
        {
          type: 'primary',
          quaternary: true,
          onClick: () => {
            RecordType.setRouteNameTypeFalse('A0507')
            handleDetail(e)
          }
        },
        {
          default: () => '详情'
        }
      ),
      h(
        NButton,
        {
          type: 'primary',
          quaternary: true,
          style: {
            display: e.fromStatusCode == 'A0603' ? 'inline-flex' : 'none'
          },
          onClick: () => handleBack(e)
        },
        {
          default: () => '撤销'
        }
      )
    ]
  }
]

//日期选择器
const dateRange = ref()
const changeDate = (e: any) => {
  if (e) {
    formInfo.startTime = new Date(e[0])
    formInfo.endTime = new Date(e[1])
  } else {
    formInfo.startTime = null
    formInfo.endTime = null
  }
}

//筛选条件
const formValue = reactive({
  startDate: null,
  endDate: null
})
const paginationReactive = reactive({
  page: 1,
  pageSize: 10,
  showSizePicker: true,
  pageSizes: [10, 20, 50, 100, 500],
  itemCount: 0,
  onChange: (page: number) => {
    paginationReactive.page = page
    queryTableData()
  },
  onUpdatePageSize: (pageSize: number) => {
    paginationReactive.pageSize = pageSize
    paginationReactive.page = 1
    queryTableData()
  }
})

// 添加重置函数
const resetQuery = () => {
  formInfo.conferenceRoomId = null
  formInfo.fromStatusCode = null
  formInfo.content = null
  formInfo.startTime = null
  formInfo.endTime = null
  queryTableData(true)
  message.success('查询条件已重置')
}

//详情
const handleDetail = (val: any) => {
  router.push({
    path: '/OA/Meeting/RoomReservationDetail',
    query: {
      id: val.id
    }
  })
}

//撤回
const modalVisible = ref(false)
const modalId = ref()
const modalCode = ref()
const handleBack = async (e: any) => {
  dialog.success({
    title: '确认撤销',
    content: '您确定要撤销这个会议室吗？此操作不可逆。',
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: () => {
      backReservation(e.id)
    }
  })
}

// 撤回消息
const backReservation = async (id) => {
  const [error, res] = await sendRequest({
    module: 'meeting',
    api: 'roomReservationRevoke',
    override: {
      data: {
        functionCode: 'A0578',
        // functionCode: 'A0602',
        resourceId: id
      }
    }
  })
  if (error) return message.error('撤回失败')
  if (res.code !== 0) return message.error('撤回失败')
  message.success('撤回成功')
  queryTableData()
}

const againBack = async () => {
  const [error, res] = await sendRequest({
    module: 'seal',
    api: 'sealApplicationBack',
    override: {
      params: {
        id: modalId.value,
        code: modalCode.value
      }
    }
  })
  if (error) return message.error(error.message)
  message.success(res.data)
  modalVisible.value = false
  queryTableData()
}

//表格数据
const tableLoading = ref(false)
const tableData: any = ref([])
const queryTableData = async (resetPage = false) => {
  if (resetPage) paginationReactive.page = 1
  tableLoading.value = true
  const [error, res] = await sendRequest({
    module: 'meeting',
    api: 'roomReservationList',
    override: {
      params: {
        ...formInfo,
        page: paginationReactive.page,
        limit: paginationReactive.pageSize
      }
    }
  })
  tableLoading.value = false
  if (error) return message.error(error.message)
  paginationReactive.itemCount = res.data?.totalCount
  const tmp: any = res.data
  tableData.value = tmp?.list
}

const keyUpDown = (e: any) =>
  e.key == 'Enter' && ((paginationReactive.page = 1), queryTableData(true))
onDeactivated(() => window.removeEventListener('keyup', keyUpDown, false))

watch(
  () => route.path,
  async () => {
    if (route.path == '/OA/Meeting/RoomReservationsList') {
      await queryTableData()
      fetchRoomList()
      window.addEventListener('keyup', keyUpDown, false)
    }
  },
  { deep: true, immediate: true }
)
</script>

<template>
  <TableView class="table">
    <template #form>
      <NSpace justify="space-between">
        <NForm
          :show-feedback="false"
          label-placement="left"
          inline
        >
          <NFormItem label="会议室:">
            <NSelect
              v-model:value="formInfo.conferenceRoomId"
              :options="roomList"
              style="width: 150px"
              clearable
            />
          </NFormItem>
          <NFormItem label="会议时间:">
            <NDatePicker
              input-readonly
              type="datetimerange"
              clearable
              v-model:value="dateRange"
              :on-update:value="changeDate"
            />
          </NFormItem>
          <NFormItem label="会议主题：">
            <NInput
              v-model:value="formInfo.content"
              clearable
            />
          </NFormItem>
          <NFormItem label="审批状态:">
            <NSelect
              v-model:value="formInfo.fromStatusCode"
              :options="statusList"
              style="width: 150px"
              clearable
            />
          </NFormItem>
          <NFormItem>
            <NButton
              type="primary"
              style="width: 78px; margin-right: 40rem"
              ghost
              @click="queryTableData(true)"
            >
              查询
            </NButton>
            <NButton
              type="primary"
              ghost
              style="width: 78px"
              @click="resetQuery"
            >
              重置
            </NButton>
          </NFormItem>
        </NForm>
      </NSpace>
    </template>

    <template #table="props">
      <NDataTable
        v-bind="props"
        :bordered="false"
        :row-key="rowKey"
        :columns="columns"
        :data="tableData"
        :loading="tableLoading"
      />
    </template>

    <template #pagination>
      <NPagination
        :page-sizes="paginationReactive.pageSizes"
        :item-count="paginationReactive.itemCount"
        :page="paginationReactive.page"
        :page-size="paginationReactive.pageSize"
        @update:page="paginationReactive.onChange"
        @update:page-size="paginationReactive.onUpdatePageSize"
        show-size-picker
        show-quick-jumper
        :suffix="() => '页'"
      >
        <template #prefix>
          <span style="font-size: 14px">共{{ paginationReactive.itemCount }}条</span>
        </template>
      </NPagination>
    </template>
  </TableView>

  <NModal
    :auto-focus="false"
    v-model:show="modalVisible"
  >
    <VDialogContent
      @close="modalVisible = false"
      @submit="againBack"
      title="撤回提示"
    >
      <div style="width: 300rem; height: 100rem; text-align: center; line-height: 100rem">
        您确定要撤回吗?
      </div>
    </VDialogContent>
  </NModal>
</template>

<style scoped lang="scss">
.table {
  height: 100%;
  padding: 29px 30px 42px;
}
</style>
